<template>
  <div :id="id" class="vditor"></div>
</template>

<script setup name="vditorEditor">
import { ref, onMounted, watch } from 'vue';
import editor from 'vditor';
import { v4 as uuidv4 } from 'uuid';
import {addFile} from "@/renderer/api/dict";


// Define props
const props = defineProps({
  height: {
    type: Number,
    default: 200
  },
  modelValue: {
    type: String,
    default: ''
  }
});

// Define emits
const emit = defineEmits(['update:modelValue']);

// Define reactive references
const id = ref(uuidv4());
const width = ref('100%');
const contentEditor = ref(null);

// Initialize Vditor editor on mount
onMounted(() => {
  contentEditor.value = new editor(id.value, {

    minHeight: props.height,
    width: width.value,
    toolbarConfig: {
      pin: true
    },
    preview: {
      maxWidth: '100%'
    },
    cdn: 'http://localhost:3123/node_modules/vditor/',
    cache: {
      enable: false
    },
    blur: (newString) => {
      emit('update:modelValue', newString);
    },
    after: () => {
      contentEditor.value.setValue(props.modelValue);
    },
    input(value) {
      console.log(value, "value")
    },
    upload: {
      accept: 'image/*,.pdf',
      token: 'X-Upload-Token',
      url: '/api/upload/editor',
      handler: (file) => {
        const formData = new FormData();
        formData.append('file', file[0]);
        addFile(formData).then((res) => {
          console.log(res.msg, 'res.msg');
          contentEditor.value.insertValue(`![image](${res.msg})`);
        });
      }
    }
  });
});

// Watch for changes in modelValue
watch(() => props.modelValue, (newValue) => {
  if (contentEditor.value && newValue !== contentEditor.value.getValue()) {
    contentEditor.value.setValue(newValue);
  }
});

// Define methods
const getValue = () => {
  return contentEditor.value ? contentEditor.value.getValue() : '';
};

const setValue = (value) => {
  if (contentEditor.value) {
    contentEditor.value.setValue(value);
  }
};
</script>

<style  scoped>
.vditor {
  width: 100% !important;
  height: 100% !important;
  border: none !important;
}
</style>